import { sys } from 'cc'
import characterLibrary from './characterLibrary'

const character = {
    setAdd: undefined,
    setMinus: undefined,
    get: undefined,
    init: undefined,
}

// 初始化背包
character.init = () => {
    let myBack = character.get()
    if(myBack.size === 0) {
        let backMap = new Map<string, number>
        for (let i of characterLibrary) {
            backMap.set(i[0], 0)
        }
        character.setAdd(backMap)
    }else {
        for (let i of characterLibrary) {
            if(!myBack.get(i[0])) {
                myBack.set(i[0], 0)
            }
        }
        character.setAdd(myBack)
    }
}

// 设置加背包
character.setAdd = (addBack: Map<string, number>) => {
    let myBack = character.get()
    for(let i of addBack) {
        if(myBack.get(i[0])) {
            myBack.get(i[0]).number += i[1]
        }else {
            myBack.set(i[0], i[1])
        }
    }
    let myBackList = []
    for(let i of myBack) {
        myBackList.push({
            uuid: i[0],
            number: i[1]
        })
    }
    sys.localStorage.setItem('myBackpack', JSON.stringify(myBackList))
}

// 设置减背包
character.setMinus = (value: Map<string, number>) => {
    sys.localStorage.setItem('myBackpack', JSON.stringify(value))
}

// 获取背包
character.get = () => {
    let myBack = sys.localStorage.getItem('myBackpack')
    if(myBack) {
        myBack = JSON.parse(myBack)
        let myBackList = new Map<string, number>
        for(let i of myBack) {
            myBackList.set(i.uuid, i.number)
        }
        return myBackList
    }else {
        return new Map<string, number>()
    }
}
character.init()
export default character